package com.caigou.modules.gallery.ui

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.adapter.CommentItemAdapter
import com.caigou.comm.base.adapter.PrizeBallItemAdapter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.CommentBean
import com.caigou.comm.base.bean.OpenPrizeVoBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.prizeBallColor
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.comm.base.widget.YearPickDialog
import com.caigou.modules.gallery.R
import com.caigou.modules.gallery.bean.GalleryDetailBean
import com.caigou.modules.gallery.databinding.ActivityGalleryDetailBinding
import com.caigou.modules.gallery.viewmodel.GalleryViewModel
import com.caigou.modules.gallery.viewmodel.LikeViewModel
import com.google.android.material.tabs.TabLayout
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

/**
 * @author #Suyghur.
 * Created on 2022/01/01
 */
@Route(path = RouterPath.Gallery.PAGE_GALLERY_DETAIL)
@AndroidEntryPoint
class GalleryDetailActivity : BaseActivity() {

    private lateinit var binding: ActivityGalleryDetailBinding
    private val galleryViewModel: GalleryViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.DATA_TYPE)
    var type = 1

    @JvmField
    @Autowired(name = AppConstants.DEPOT_ID)
    var depotId = 1

    @JvmField
    @Autowired(name = AppConstants.DEPOT_NAME)
    var depotIdName = ""

    @JvmField
    @Autowired(name = AppConstants.YEAR)
    var year = ""

    private val periods = mutableListOf<String>()
    private var period: Int = 0

    @JvmField
    @Autowired(name = AppConstants.PERIOD)
    var tranPeriod: Int = 0

    private var collect = false

    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var sort = 0

    private var dataId = 0

    private val prizeAdapter: PrizeBallItemAdapter by lazy {
        PrizeBallItemAdapter(mutableListOf())
    }

    private val commentItemAdapter: CommentItemAdapter by lazy {
        CommentItemAdapter(mutableListOf())
    }

    private val yearDialog by lazy {
        YearPickDialog(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityGalleryDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.galleryDetailLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        if (TextUtils.isEmpty(year)) {
            year = Calendar.getInstance().get(Calendar.YEAR).toString()
        }

        binding.galleryDetailSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchGallyDetail()
            }
        }

        binding.galleryDetailTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.apply {
                    period = periods[position].toInt()
                    fetchGallyDetail()
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })

        binding.galleryDetailBtnYear.text = year
        binding.galleryDetailBtnYear.setOnClickListener {
            yearDialog.show()
        }
        yearDialog.tvConfirm.setOnClickListener {
            year = yearDialog.getYear().toString()
            binding.galleryDetailBtnYear.text = year
            fetchPeriodList()
            yearDialog.dismiss()
        }

        commentItemAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                commentItemAdapter.loadMoreModule.isEnableLoadMore = true
                fetchCommentList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.galleryDetailRecyclerViewComment.run {
            layoutManager = LinearLayoutManager(this@GalleryDetailActivity)
            adapter = commentItemAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@GalleryDetailActivity))
        }
        commentItemAdapter.setOnItemChildClickListener { _, view, position ->
            val item = commentItemAdapter.data[position]
            when (view.id) {
                R.id.item_comment_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.replyUserInfoVo.userId)
                        .navigation()
                }
                R.id.item_comment_ll_content -> {
                    ARouter.getInstance().build(RouterPath.Gallery.PAGE_COMMENT_DETAIL)
                        .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                        .withInt(AppConstants.DATA_TYPE, item.type)
                        .navigation()
                }
                R.id.item_comment_iv_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        if (item.like) {
                            showToast("您已经点过赞了")
                        } else {
                            likeViewModel.setCommentLike(item.type, item.replyId, AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId)
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_btn_reply -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        ARouter.getInstance()
                            .build(RouterPath.Gallery.PAGE_COMMENT_REPLY)
                            .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                            .withObject(AppConstants.COMMENT_ROOT_ITEM_BEAN, item)
                            .withInt(AppConstants.DATA_TYPE, type)
                            .navigation()
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.galleryDetailRgSelector.setOnCheckedChangeListener { group, _ ->
            sort = when (group.checkedRadioButtonId) {
                binding.galleryDetailBtnSequential.id -> 1
                binding.galleryDetailBtnReverse.id -> 0
                else -> 0
            }
            page = 1
            fetchCommentList()
        }

        binding.galleryDetailBtnCollect.setOnClickListener {
            val userId = if (AppBackgroundInfo.instance.hasLogin) {
                AppBackgroundInfo.instance.userBean!!.userId
            } else {
                ""
            }
            galleryViewModel.collect(type, depotId, userId)
        }

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            fetchCommentList()
        }

        binding.galleryDetailTvBack.setOnClickListener {
            finish()
        }

        binding.galleryDetailTvTitle.text = depotIdName

        fetchPeriodList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(galleryViewModel.periodListLiveData, ::handleGetPeriodList)
        observe(galleryViewModel.galleryDetailLiveData, ::handleGetGalleryDetail)
        observe(galleryViewModel.commentListLiveData, ::handleGetCommentList)
        observe(galleryViewModel.collectLiveData, ::handleCollect)
        observe(likeViewModel.detailLikeLiveData, ::handleSetDetailLike)
        observe(likeViewModel.commentLikeLiveData, ::handleSetCommentLike)
    }

    private fun handleGetPeriodList(result: Resource<MutableList<String>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    binding.galleryDetailTabLayout.removeAllTabs()
                    periods.clear()
                    if (isNotEmpty()) {
                        binding.galleryDetailLlEmptyContent.visibility = View.GONE
                        binding.galleryDetailLlContent.visibility = View.VISIBLE
                        periods.addAll(this)
                        period = this[0].toInt()
                        forEachIndexed { idx, value ->
                            val tab = binding.galleryDetailTabLayout.newTab()
                            tab.text = value
                            binding.galleryDetailTabLayout.addTab(tab, idx)
                        }
                        if (tranPeriod != 0 && periods.isNotEmpty()) {
                            val index = periods.indexOf(tranPeriod.toString())
                            binding.galleryDetailTabLayout.selectTab(binding.galleryDetailTabLayout.getTabAt(index))
                        }
                        fetchGallyDetail()
                    } else {
                        binding.galleryDetailLlEmptyContent.visibility = View.VISIBLE
                        binding.galleryDetailLlContent.visibility = View.GONE
                    }
                }
            }
        }
    }

    private fun handleGetGalleryDetail(result: Resource<GalleryDetailBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取图库细信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.galleryDetailLlEmptyContent.visibility = View.VISIBLE
                    binding.galleryDetailLlContent.visibility = View.GONE
                } else {
                    binding.galleryDetailLlEmptyContent.visibility = View.GONE
                    binding.galleryDetailLlContent.visibility = View.VISIBLE
                    dataId = result.data!!.detailId
                    collect = result.data!!.collect
                    fetchCommentList()
                    handleDetailUI(result.data!!)
                }
            }
        }
    }

    private fun handleGetCommentList(result: Resource<CommentBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取评论列表异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.galleryDetailLlEmpty.visibility = View.VISIBLE
                    binding.galleryDetailRecyclerViewComment.visibility = View.GONE
                    return
                }
                if (result.data!!.list.isNullOrEmpty()) {
                    binding.galleryDetailLlEmpty.visibility = View.VISIBLE
                    binding.galleryDetailRecyclerViewComment.visibility = View.GONE
                } else {
                    binding.galleryDetailLlEmpty.visibility = View.GONE
                    binding.galleryDetailRecyclerViewComment.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    commentItemAdapter.setList(result.data!!.list)
                } else {
                    commentItemAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    commentItemAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleCollect(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("收藏异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (collect) {
                    collect = false
                    binding.galleryDetailBtnCollect.text = "收藏"
                } else {
                    collect = true
                    binding.galleryDetailBtnCollect.text = "取消收藏"
                }
            }
        }
    }

    private fun handleSetDetailLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchGallyDetail()
                }
            }
        }
    }

    private fun handleSetCommentLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.galleryDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchCommentList()
                }
            }
        }
    }

    private fun handleDetailUI(bean: GalleryDetailBean) {
        handlePrize(bean.openPrizeVo)
        collect = bean.collect
        binding.galleryDetailTvTime.text = bean.createTime
        binding.galleryDetailTvBrowseNum.text = bean.browseCount.toString()

        ImageLoader.load(this, bean.cover, binding.galleryDetailIvCover)

        if (AppBackgroundInfo.instance.hasLogin) {
            if (TextUtils.isEmpty(AppBackgroundInfo.instance.userBean!!.headImg)) {
                binding.galleryDetailIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this, AppBackgroundInfo.instance.userBean!!.headImg, binding.galleryDetailIvMyAvatar)
            }
        } else {
            binding.galleryDetailIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
        }


        binding.galleryDetailTvLikeNum.text = bean.niceCount.toString()
        if (bean.like) {
            binding.galleryDetailIvLike.setImageResource(R.drawable.img_gallery_like)
            binding.galleryDetailTvLikeNum.setTextColor(Color.parseColor("#FE6880"))
        } else {
            binding.galleryDetailIvLike.setImageResource(R.drawable.img_gallery_unlike)
            binding.galleryDetailTvLikeNum.setTextColor(Color.parseColor("#505050"))
        }
        binding.galleryDetailLlLike.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                if (bean.like) {
                    showToast("您已经点过赞了")
                } else {
                    likeViewModel.setDetailLike(bean.depotId, bean.detailId, type, AppBackgroundInfo.instance.userBean!!.userId)
                }
            } else {
                showToast("请您先登录")
            }
        }

        binding.galleryDetailTvCommentNum.text = bean.replyCount.toString()

        binding.galleryDetailBtnReply.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Gallery.PAGE_REPLY)
                    .withInt(AppConstants.DEPOT_ID, bean.depotId)
                    .withInt(AppConstants.DETAIL_ID, bean.detailId)
                    .withInt(AppConstants.DATA_TYPE, type)
                    .withString(AppConstants.RECEIVER_ID, "")
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.galleryDetailLlLike.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                likeViewModel.setDetailLike(bean.depotId, bean.detailId, type, AppBackgroundInfo.instance.userBean!!.userId)
            } else {
                showToast("请您先登录")
            }
        }

        binding.galleryDetailLlComment.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Gallery.PAGE_REPLY)
                    .withInt(AppConstants.DEPOT_ID, bean.depotId)
                    .withInt(AppConstants.DETAIL_ID, bean.detailId)
                    .withInt(AppConstants.DATA_TYPE, type)
                    .withString(AppConstants.RECEIVER_ID, "")
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.galleryDetailLlShare.setOnClickListener {

        }
    }

    private fun handlePrize(bean: OpenPrizeVoBean) {
        if (bean.prizeList.isNullOrEmpty()) {
            binding.galleryDetailTvPrizeTitle.visibility = View.GONE
            binding.galleryDetailLlPrize.visibility = View.GONE
        } else {
            binding.galleryDetailTvPrizeTitle.visibility = View.VISIBLE
            binding.galleryDetailLlPrize.visibility = View.VISIBLE

            binding.galleryDetailTvPrizeTitle.text = "第${bean.period}期开奖结果"
            binding.galleryDetailRecyclerViewPrize.run {
                layoutManager = GridLayoutManager(this@GalleryDetailActivity, 6)
                adapter = prizeAdapter
                itemAnimator = DefaultItemAnimator()
                addItemDecoration(SpaceItemDecoration(this@GalleryDetailActivity))
            }

            val size = bean.prizeList.size
            val balls = bean.prizeList.slice(0..size - 2)
            prizeAdapter.setList(balls)
            val lastBall = bean.prizeList[size - 1]
            binding.galleryDetailPrizeTvNum.text = lastBall.number
            binding.galleryDetailPrizeTvNum.setBackgroundResource(prizeBallColor(lastBall.numberColor))
            binding.galleryDetailPrizeTvDesc.text = lastBall.animalName
        }
    }


    private fun fetchPeriodList() {
        galleryViewModel.getPeriodList(year.toInt())
    }

    private fun fetchGallyDetail() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        galleryViewModel.getGalleryDetail(depotId, period, type, userId)

    }

    private fun fetchCommentList() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        galleryViewModel.getCommentList(page, limit, depotId, dataId, type, sort, userId)
    }
}